package com.peanut.huibutie.openapi;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.PropertyNamingStrategy;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.peanut.huibutie.common.AppConfig;
import com.peanut.huibutie.common.HttpInvoker;
import com.peanut.huibutie.common.OpenApiResult;
import com.peanut.huibutie.common.UserContext;
import com.peanut.huibutie.entity.RefundVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 支付结果查询
 *
 * @see <a href="https://www.showdoc.com.cn/huibutie/10933753683106602">API</a>
 */
@Slf4j
@Service
public class Refund {
    @Resource
    private HttpInvoker httpInvoker;
    @Resource
    private UserContext userContext;
    @Resource
    private CreateAccessToken createAccessToken;


    public void invoke(RefundVO refundVO) {

        JSONObject map = (JSONObject) JSONObject.toJSON(refundVO, new SerializeConfig() {{
            setPropertyNamingStrategy(PropertyNamingStrategy.SnakeCase);
        }});
        map.put("open_id", userContext.getContext().getOpenId());
        map.put("access_token", userContext.getContext().getAccessToken());
        map.put("timestamp", System.currentTimeMillis());
        OpenApiResult<JSONObject> openApiResult = httpInvoker.sendPost(AppConfig.Refund_URL, map, JSONObject.class);

        if (openApiResult.isSuccess()) {
            JSONObject data = openApiResult.getData();
            String refundStatus = data.getString("refund_status");
            log.info("调用退款API，退款请求单号={},响应的退款状态={}", refundVO.getOuterRefundNo(), refundStatus);
        } else if (openApiResult.isAuthError()) {//token校验错误。重新获取token。
            createAccessToken.invoke();
            invoke(refundVO);
        } else {
            log.info("调用退款API，返回错误：{}", openApiResult);
            return;
        }
    }
}
